<template>
	<custom-navigation-bar class="nav-bar" title="核销记录" :back="true">
		<share-element class="box-wrp" key="order" transition-on-gesture shuttle-on-push="from">
			<text class="">
				预约订单
			</text>
		</share-element>
	</custom-navigation-bar>
	<view class="reservation-order">
		<!-- 搜索和筛选区域 -->
		<view class="filter-bar flex-row">
			<view class="search-box">
				<image src="/static/icons/search.png" mode="widthFix" class="search-icon"></image>
				<input type="text" placeholder="搜索服务名称或用户" v-model="searchKeyword" @input="handleSearch"
					class="search-input" />
			</view>

			<view class="filter-btn" @tap="showFilter = !showFilter">
				<image src="/static/icons/filter.png" mode="widthFix" class="filter-icon"></image>
				<text class="filter-text">筛选</text>
			</view>
		</view>

		<!-- 状态筛选快捷栏 -->
		
		<bs-btntabs @onTap='onTap' :statusTypes='statusTypes' :selectedStatus='selectedStatus'></bs-btntabs>

		<!-- 筛选面板 -->
		<view class="filter-panel" v-if="showFilter">
			<view class="filter-section">
				<view class="filter-title">服务类型</view>
				<view class="filter-options flex-row">
					<view class="filter-option" v-for="(item, index) in serviceTypes" :key="index"
						:class="{ 'active': selectedService === index }" @tap="selectedService = index">
						{{ item }}
					</view>
				</view>
			</view>

			<view class="filter-section">
				<view class="filter-title">预约时间</view>
				<view class="date-picker flex-row">
					<picker mode="date" start="2023-01-01" end="2099-12-31" @change="onStartDateChange">
						<view class="picker-view">
							{{ startDate || '开始日期' }}
						</view>
					</picker>
					<view class="date-separator">至</view>
					<picker mode="date" start="2023-01-01" end="2099-12-31" @change="onEndDateChange">
						<view class="picker-view">
							{{ endDate || '结束日期' }}
						</view>
					</picker>
				</view>
			</view>

			<view class="filter-actions flex-row">
				<button class="reset-btn" @tap="resetFilter">重置</button>
				<button class="confirm-btn" @tap="confirmFilter">确认</button>
			</view>
		</view>
	</view>
	<!-- 订单列表 -->
	<bs-scroll style="flex: 1;" @onScrollToLower='loadMore' :load='loading' bg='#f5f5f5'>
		<view class="reservation-order">
			<view class="order-list ">
				<view class="order-item" v-for="(order, index) in filteredOrders" :key="index" @tap="viewDetail(order)">
					<view class="order-header justify-between flex-row">
						<view class="service-name">{{ order.serviceName }}</view>
						<view class="order-status" :class="[getStatusClass(order.status)]">{{ order.status }}</view>
					</view>

					<view class="order-body">
						<view class="order-info flex-row">
							<text class="info-label">用户：</text>
							<text class="info-value">{{ order.userName }}</text>
						</view>
						<view class="order-info flex-row">
							<text class="info-label ">预约时间：</text>
							<text class="info-value">{{ order.reserveTime }}</text>
						</view>
						<view class="order-info flex-row">
							<text class="info-label ">订单编号：</text>
							<text class="info-value">{{ formatOrderNo(order.orderNo) }}</text>
						</view>
						<view class="order-info flex-row">
							<text class="info-label">联系人/电话：</text>
							<text class="info-value">{{ order.contactPerson }} /
								{{ formatPhone(order.contactPhone) }}</text>
						</view>
					</view>

					<view class="order-footer flex-row">
						<view class="order-price">¥{{ order.price.toFixed(2) }}</view>
						<!-- <image src="/static/icons/arrow-right.png" mode="widthFix" class="arrow-icon"></image> -->
					</view>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-if="filteredOrders.length === 0 && !loading">
					<!-- <image src="/static/icons/empty-order.png" mode="widthFix" class="empty-icon"></image> -->
					<text class="empty-text">暂无预约订单</text>
				</view>

				<!-- 加载中 -->
				<view class="loading-state" v-if="loading">
					<bs-load></bs-load>
					<text class="loading-text">加载中...</text>
				</view>
				<!-- 加载更多 -->
				<view class="load-more" v-if="hasMore && !loading" @tap="loadMore">
					<text>加载更多</text>
				</view>
			</view>
		</view>
	</bs-scroll>

</template>

<script>
	import {
		getCurrentInstance
	} from "vue"
	const GestureState = {
		POSSIBLE: 0,
		BEGIN: 1,
		ACTIVE: 2,
		END: 3,
		CANCELLED: 4
	}
	const {
		Easing,
		spring,
		shared,
		timing,
		runOnUI,
		runOnJS,
		sequence
	} = wx.worklet
	const x = shared(0);
	const y = shared(0);
	const scale = shared(1);
	const pressed = shared(false);
	// 定义可以触发的事件
	const easing = Easing.ease
	export default {
		data() {
			return {
				// 搜索和筛选条件
				searchKeyword: '',
				showFilter: false,
				statusTypes: ['全部', '待确认', '已确认', '已完成', '已取消'],
				selectedStatus: 0,
				serviceTypes: ['全部', '国际贵宾通道', '国内贵宾通道', '易登机优享通道(2)', '易登机优享通道(3)', '易登机优享通道(4)'],
				selectedService: 0,
				startDate: '',
				endDate: '',

				// 数据相关
				orders: [],
				filteredOrders: [],
				page: 1,
				pageSize: 10,
				hasMore: true,
				loading: false
			}
		},
	
		
		onLoad() {
			// 检查权限
			// this.checkPermission();
			// 加载数据
			this.loadOrders();
		},
		onReady() {
			this.initApplyAnimatedCartStyle()
			this.headerAnimate()
		},
		onReachBottom() {
			this.loadMore();
		},

		methods: {
			onTap(e){
				this.selectedStatus = e
			},
			
			// 返回上一页
			navBack() {
				uni.navigateBack();
			},

			// 检查权限
			checkPermission() {
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo || userInfo.role !== 'staff') {
					uni.showToast({
						title: '没有查看权限',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				}
			},

			// 加载预约订单
			loadOrders() {
				if (this.loading) return;

				this.loading = true;
				// 模拟API请求
				setTimeout(() => {
					// 生成模拟数据
					const mockData = [];
					for (let i = 0; i < this.pageSize; i++) {
						const id = (this.page - 1) * this.pageSize + i + 1;
						const serviceTypes = ['国际贵宾通道', '国内贵宾通道', '易登机优享通道(2)', '易登机优享通道(3)', '易登机优享通道(4)'];
						const statusTypes = ['待确认', '已确认', '已完成', '已取消'];

						const randomType = Math.floor(Math.random() * 5);
						const randomStatus = Math.floor(Math.random() * 4);
						const randomDays = Math.floor(Math.random() * 30);

						// 计算预约时间（未来或过去的日期）
						const reserveDate = new Date();
						if (randomStatus === 2 || randomStatus === 3) { // 已完成或已取消的订单是过去的时间
							reserveDate.setDate(reserveDate.getDate() - randomDays);
						} else { // 待确认和已确认的是未来的时间
							reserveDate.setDate(reserveDate.getDate() + randomDays);
						}

						mockData.push({
							id,
							orderNo: `ORD${Date.now() + id}`,
							serviceName: serviceTypes[randomType],
							userName: `用户${Math.floor(Math.random() * 1000)}`,
							reserveTime: this.formatTime(reserveDate),
							contactPerson: `联系人${Math.floor(Math.random() * 1000)}`,
							contactPhone: `13${Math.floor(Math.random() * 100000000)}`,
							status: statusTypes[randomStatus],
							userType: ['散客', '固有会员', '散客储值'][Math.floor(Math.random() * 3)],
							price: Math.floor(Math.random() * 5) * 100 + 100,
							createTime: this.formatTime(new Date(Date.now() - Math.random() * 30 * 24 *
								60 * 60 * 1000))
						});
					}

					if (this.page === 1) {
						this.orders = mockData;
					} else {
						this.orders = [...this.orders, ...mockData];
					}

					// 应用筛选条件
					this.applyFilters();

					// 模拟数据到底
					if (this.page >= 3) {
						this.hasMore = false;
					}

					this.loading = false;
				}, 1000);
			},

			// 加载更多
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.page++;
					this.loadOrders();
				}
			},

			// 处理搜索
			handleSearch() {
				this.applyFilters();
			},

			// 开始日期选择
			onStartDateChange(e) {
				this.startDate = e.detail.value;
			},

			// 结束日期选择
			onEndDateChange(e) {
				this.endDate = e.detail.value;
			},

			// 重置筛选条件
			resetFilter() {
				this.selectedStatus = 0;
				this.selectedService = 0;
				this.startDate = '';
				this.endDate = '';
				this.searchKeyword = '';
				this.applyFilters();
			},

			// 确认筛选
			confirmFilter() {
				this.showFilter = false;
				this.applyFilters();
			},

			// 应用筛选条件
			applyFilters() {
				let result = [...this.orders];

				// 状态筛选
				if (this.selectedStatus > 0) {
					const status = this.statusTypes[this.selectedStatus];
					result = result.filter(item => item.status === status);
				}

				// 服务类型筛选
				if (this.selectedService > 0) {
					const serviceName = this.serviceTypes[this.selectedService];
					result = result.filter(item => item.serviceName === serviceName);
				}

				// 搜索关键词筛选
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase();
					result = result.filter(item =>
						item.serviceName.toLowerCase().includes(keyword) ||
						item.userName.toLowerCase().includes(keyword) ||
						item.contactPerson.toLowerCase().includes(keyword)
					);
				}

				// 日期范围筛选
				if (this.startDate) {
					result = result.filter(item => new Date(item.reserveTime) >= new Date(this.startDate));
				}

				if (this.endDate) {
					result = result.filter(item => new Date(item.reserveTime) <= new Date(this.endDate));
				}

				this.filteredOrders = result;
			},

			// 查看详情
			viewDetail(order) {
				uni.navigateTo({
					url: `/pages/reservation/detail?info=${encodeURIComponent(JSON.stringify(order))}`
				});
			},

			// 格式化订单号（中间隐藏）
			formatOrderNo(orderNo) {
				if (orderNo.length <= 10) return orderNo;
				return orderNo.substr(0, 5) + '*****' + orderNo.substr(-5);
			},

			// 格式化手机号（中间隐藏）
			formatPhone(phone) {
				if (phone.length !== 11) return phone;
				return phone.substr(0, 3) + '****' + phone.substr(-4);
			},

			// 格式化时间
			formatTime(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');
				return `${year}-${month}-${day} ${hour}:${minute}`;
			},

			// 根据状态获取样式类
			getStatusClass(status) {
				switch (status) {
					case '待确认':
						return 'pending';
					case '已确认':
						return 'confirmed';
					case '已完成':
						return 'completed';
					case '已取消':
						return 'cancelled';
					default:
						return '';
				}
			}
		}
	}
</script>

<style lang="scss">
	.reservation-order {
		background-color: #f5f5f5;

		.filter-bar {
			display: flex;
			padding: 20rpx;
			background-color: #fff;
			border-bottom: 1rpx solid #eee;

			.search-box {
				flex: 1;
				display: flex;
				align-items: center;
				background-color: #f5f5f5;
				border-radius: 80rpx;
				padding: 0 30rpx;
				height: 70rpx;

				.search-icon {
					width: 30rpx;
					height: 30rpx;
					margin-right: 15rpx;
					opacity: 0.5;
				}

				.search-input {
					flex: 1;
					font-size: 26rpx;
					color: #333;
					height: 100%;
				}
			}

			.filter-btn {
				width: 120rpx;
				height: 70rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 20rpx;

				.filter-icon {
					width: 30rpx;
					height: 30rpx;
					margin-right: 5rpx;
				}

				.filter-text {
					font-size: 26rpx;
					color: #333;
				}
			}
		}

		

		.filter-panel {
			background-color: #fff;
			border-bottom: 1rpx solid #eee;
			padding: 20rpx;

			.filter-section {
				margin-bottom: 30rpx;

				&:last-child {
					margin-bottom: 20rpx;
				}

				.filter-title {
					font-size: 28rpx;
					font-weight: 500;
					color: #333;
					margin-bottom: 15rpx;
				}

				.filter-options {
					display: flex;
					flex-wrap: wrap;
					gap: 15rpx;

					.filter-option {
						padding: 10rpx 20rpx;
						background-color: #f5f5f5;
						border-radius: 60rpx;
						font-size: 24rpx;
						color: #666;

						&.active {
							background-color: #e8f0fe;
							color: #1a73e8;
						}
					}
				}

				.date-picker {
					display: flex;
					align-items: center;
					gap: 20rpx;

					.picker-view {
						flex: 1;
						height: 70rpx;
						line-height: 70rpx;
						background-color: #f5f5f5;
						border-radius: 8rpx;
						padding: 0 20rpx;
						font-size: 26rpx;
						color: #333;
					}

					.date-separator {
						font-size: 28rpx;
						color: #999;
					}
				}
			}

			.filter-actions {
				display: flex;
				gap: 20rpx;
				margin-top: 20rpx;

				.reset-btn {
					flex: 1;
					height: 80rpx;
					line-height: 80rpx;
					background-color: #f5f5f5;
					color: #666;
					font-size: 28rpx;
					border-radius: 8rpx;
				}

				.confirm-btn {
					flex: 1;
					height: 80rpx;
					line-height: 80rpx;
					background-color: #1a73e8;
					color: #fff;
					font-size: 28rpx;
					border-radius: 8rpx;
				}
			}
		}

		.order-list {
			padding: 20rpx;

			.order-item {
				background-color: #fff;
				border-radius: 16rpx;
				padding: 25rpx;
				margin-bottom: 20rpx;
				box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
				position: relative;

				&:last-child {
					margin-bottom: 0;
				}

				.order-header {
					display: flex;
					justify-content: space-between;
					margin-bottom: 20rpx;

					.service-name {
						font-size: 28rpx;
						font-weight: 500;
						color: #333;
					}

					.order-status {
						font-size: 24rpx;
						padding: 5rpx 15rpx;
						border-radius: 60rpx;

						&.pending {
							color: #ff7d00;
							background-color: #fff7e6;
						}

						&.confirmed {
							color: #0066ff;
							background-color: #e6f0ff;
						}

						&.completed {
							color: #07c160;
							background-color: #f6ffed;
						}

						&.cancelled {
							color: #999;
							background-color: #f2f2f2;
						}
					}
				}

				.order-body {
					.order-info {
						display: flex;
						margin-bottom: 15rpx;

						&:last-child {
							margin-bottom: 0;
						}

						.info-label {
							font-size: 24rpx;
							color: #999;
							width: 160rpx;
						}

						.info-value {
							font-size: 24rpx;
							color: #666;
							flex: 1;
						}
					}
				}

				.order-footer {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 20rpx;
					padding-top: 20rpx;
					border-top: 1rpx dashed #eee;

					.order-price {
						font-size: 28rpx;
						font-weight: 500;
						color: #ff4d4f;
					}

					.arrow-icon {
						width: 24rpx;
						height: 24rpx;
						opacity: 0.5;
					}
				}
			}

			.empty-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 100rpx 0;

				.empty-icon {
					width: 150rpx;
					height: 150rpx;
					opacity: 0.3;
					margin-bottom: 30rpx;
				}

				.empty-text {
					font-size: 28rpx;
					color: #999;
				}
			}

			.loading-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 100rpx 0;

				.loading-spinner {
					width: 50rpx;
					height: 50rpx;
					border: 5rpx solid rgba(26, 115, 232, 0.1);
					border-radius: 50%;
					border-top-color: #1a73e8;
					animation: spin 1s ease-in-out infinite;
					margin-bottom: 30rpx;
				}

				.loading-text {
					font-size: 28rpx;
					color: #999;
				}
			}
		}

		.load-more {
			padding: 30rpx 0;
			text-align: center;
			font-size: 26rpx;
			color: #1a73e8;
			background-color: #fff;
			margin: 20rpx;
			border-radius: 16rpx;
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}
</style>